package com.seecen.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.common.BaseResponse;
import com.seecen.common.ResultUtils;
import com.seecen.exception.ErrorCode;
import com.seecen.pojo.entity.CurtainOrder;
import com.seecen.service.CurtainOrderService;
import com.seecen.mapper.CurtainOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Date;
import java.util.Map;

/**
* @author admin
* @description 针对表【curtain_order(窗帘安装订单表)】的数据库操作Service实现
* @createDate 2025-10-22 15:30:48
*/
@Slf4j
@Service
public class CurtainOrderServiceImpl extends ServiceImpl<CurtainOrderMapper, CurtainOrder>
        implements CurtainOrderService {
    
    @Autowired
    private CurtainOrderMapper curtainOrderMapper;

    @Override
    public BaseResponse<?> createCurtainOrder(Map<String, Object> orderData) {
        try {
            log.info("=== CurtainOrderServiceImpl.createCurtainOrder 开始 ===");
            log.info("接收到的窗帘订单数据: {}", orderData);
            
            // 从前端数据创建订单对象
            CurtainOrder order = this.buildCurtainOrderFromData(orderData);
            
            return this.saveCurtainOrder(order);
            
        } catch (Exception e) {
            log.error("创建窗帘订单异常", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "创建窗帘订单时发生错误: " + e.getMessage());
        }
    }

    @Override
    public BaseResponse<?> getCurtainOrderDetail(Long orderId) {
        try {
            log.info("=== CurtainOrderServiceImpl.getCurtainOrderDetail 开始 ===");
            log.info("获取窗帘订单详情，订单ID: {}", orderId);
            
            // 参数校验
            if (orderId == null) {
                log.error("订单ID为空");
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "订单ID不能为空");
            }
            
            // 查询订单
            CurtainOrder order = this.getById(orderId);
            if (order == null) {
                log.error("窗帘订单不存在，订单ID: {}", orderId);
                return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "订单不存在");
            }
            
            // 检查订单是否被删除
            if (order.getIsdeleted() != null && order.getIsdeleted() == 1) {
                log.error("窗帘订单已被删除，订单ID: {}", orderId);
                return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "订单已被删除");
            }
            
            log.info("成功获取窗帘订单详情: {}", order);
            return ResultUtils.success(order);
            
        } catch (Exception e) {
            log.error("获取窗帘订单详情异常，订单ID: {}", orderId, e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取订单详情时发生错误");
        }
    }

    @Override
    public BaseResponse<?> updateCurtainOrder(Long orderId, Map<String, Object> orderData) {
        try {
            log.info("=== CurtainOrderServiceImpl.updateCurtainOrder 开始 ===");
            log.info("更新窗帘订单ID: {}, 数据: {}", orderId, orderData);
            
            // 参数校验
            if (orderId == null) {
                log.error("订单ID为空");
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "订单ID不能为空");
            }
            
            // 检查订单是否存在
            CurtainOrder existingOrder = this.getById(orderId);
            if (existingOrder == null) {
                log.error("窗帘订单不存在，订单ID: {}", orderId);
                return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "订单不存在");
            }
            
            // 检查订单是否可以修改
            if (existingOrder.getStatus() != 0) {
                log.error("窗帘订单状态不允许修改，当前状态: {}", existingOrder.getStatus());
                return ResultUtils.error(ErrorCode.OPERATION_ERROR, "订单状态不允许修改");
            }
            
            // 从请求数据构建更新的订单对象
            CurtainOrder updatedOrder = this.buildCurtainOrderFromData(orderData);
            updatedOrder.setOrderid(orderId);
            updatedOrder.setCreatetime(existingOrder.getCreatetime());
            updatedOrder.setUpdatetime(new Date());
            updatedOrder.setUserid(existingOrder.getUserid());
            updatedOrder.setServiceid(existingOrder.getServiceid());
            
            // 验证更新的订单数据
            BaseResponse<?> validationResult = this.validateCurtainOrderForUpdate(updatedOrder);
            if (validationResult.getCode() != 200) {
                return validationResult;
            }
            
            // 执行更新
            boolean updateResult = this.updateById(updatedOrder);
            if (!updateResult) {
                log.error("数据库更新窗帘订单失败，订单ID: {}", orderId);
                return ResultUtils.error(ErrorCode.OPERATION_ERROR, "更新订单失败");
            }
            
            log.info("窗帘订单更新成功，订单ID: {}", orderId);
            return ResultUtils.success(orderId);
            
        } catch (Exception e) {
            log.error("更新窗帘订单异常，订单ID: {}", orderId, e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "更新订单时发生错误: " + e.getMessage());
        }
    }

    /**
     * 从前端数据构建窗帘订单对象
     */
    private CurtainOrder buildCurtainOrderFromData(Map<String, Object> orderData) {
        CurtainOrder order = new CurtainOrder();
        
        // 设置用户ID和服务ID
        Object userIdObj = orderData.get("userId");
        Object serviceIdObj = orderData.get("serviceId");
        
        if (userIdObj != null) {
            if (userIdObj instanceof Number) {
                order.setUserid(((Number) userIdObj).longValue());
            } else {
                order.setUserid(Long.parseLong(userIdObj.toString()));
            }
        }
        
        if (serviceIdObj != null) {
            if (serviceIdObj instanceof Number) {
                order.setServiceid(((Number) serviceIdObj).longValue());
            } else {
                order.setServiceid(Long.parseLong(serviceIdObj.toString()));
            }
        }
        
        // 设置基本订单信息
        order.setAddress((String) orderData.get("address"));
        order.setPictures((String) orderData.get("pictures"));
        order.setDemandDescription((String) orderData.get("demandDescription"));
        
        // 设置地区信息
        Object provinceIdObj = orderData.get("provinceId");
        Object cityIdObj = orderData.get("cityId");
        if (provinceIdObj != null) {
            order.setProvinceId(Long.parseLong(provinceIdObj.toString()));
        }
        if (cityIdObj != null) {
            order.setCityId(Long.parseLong(cityIdObj.toString()));
        }
        
        // 设置服务时间
        String serviceTimeStr = (String) orderData.get("serviceTime");
        if (serviceTimeStr != null && !serviceTimeStr.trim().isEmpty()) {
            try {
                Date serviceTime = this.parseServiceTime(serviceTimeStr);
                order.setServiceTime(serviceTime);
                log.info("成功解析窗帘订单服务时间: {}", serviceTime);
            } catch (Exception e) {
                log.warn("解析窗帘订单服务时间失败: {}, 错误: {}", serviceTimeStr, e.getMessage());
                order.setServiceTime(new Date());
            }
        }
        
        // 设置窗帘安装特有字段
        Object curtainQuantityObj = orderData.get("curtainQuantity");
        if (curtainQuantityObj != null) {
            order.setCurtainQuantity(Integer.parseInt(curtainQuantityObj.toString()));
        }
        
        order.setItemType((String) orderData.get("itemType"));
        order.setInstallHeight((String) orderData.get("installHeight"));
        order.setTrackType((String) orderData.get("trackType"));
        order.setWallMaterial((String) orderData.get("wallMaterial"));
        order.setNeedHangCurtain((String) orderData.get("needHangCurtain"));
        
        Object trackLengthObj = orderData.get("trackLength");
        if (trackLengthObj != null && !trackLengthObj.toString().trim().isEmpty()) {
            order.setTrackLength(Double.parseDouble(trackLengthObj.toString()));
        }
        
        // 设置其他字段
        Object fastestArrivalTimeObj = orderData.get("fastestArrivalTime");
        if (fastestArrivalTimeObj != null) {
            order.setFastestArrivalTime(Integer.parseInt(fastestArrivalTimeObj.toString()));
        }
        
        // 设置默认值
        order.setStatus(0);
        order.setCreatetime(new Date());
        order.setUpdatetime(new Date());
        order.setIsdeleted(0);
        
        log.info("构建的窗帘订单对象: {}", order);
        return order;
    }

    /**
     * 保存窗帘订单（包含业务逻辑验证）
     */
    private BaseResponse<?> saveCurtainOrder(CurtainOrder order) {
        try {
            log.info("=== 保存窗帘订单开始 ===");
            log.info("窗帘订单用户ID: {}", order.getUserid());
            log.info("窗帘订单服务ID: {}", order.getServiceid());
            
            // 基础参数校验
            if (order.getUserid() == null) {
                log.error("用户ID为空");
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "用户ID不能为空");
            }
            if (order.getServiceid() == null) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "服务ID不能为空");
            }
            if (order.getAddress() == null || order.getAddress().trim().isEmpty()) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "服务地址不能为空");
            }
            if (order.getItemType() == null || order.getItemType().trim().isEmpty()) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "物品类型不能为空");
            }
            if (order.getDemandDescription() == null || order.getDemandDescription().trim().isEmpty()) {
                return ResultUtils.error(ErrorCode.PARAMS_ERROR, "需求说明不能为空");
            }

            // 保存订单
            log.info("准备保存窗帘订单到数据库: {}", order);
            boolean saveResult = this.save(order);
            log.info("数据库保存结果: {}", saveResult);
            
            if (!saveResult) {
                log.error("数据库保存窗帘订单失败");
                return ResultUtils.error(ErrorCode.OPERATION_ERROR, "创建窗帘订单失败");
            }

            log.info("窗帘订单创建成功, 订单ID: {}", order.getOrderid());
            return ResultUtils.success(order.getOrderid());

        } catch (Exception e) {
            log.error("创建窗帘订单异常", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "创建窗帘订单时发生错误");
        }
    }

    /**
     * 验证窗帘订单更新数据
     */
    private BaseResponse<?> validateCurtainOrderForUpdate(CurtainOrder order) {
        if (order.getAddress() == null || order.getAddress().trim().isEmpty()) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "服务地址不能为空");
        }
        if (order.getItemType() == null || order.getItemType().trim().isEmpty()) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "物品类型不能为空");
        }
        if (order.getDemandDescription() == null || order.getDemandDescription().trim().isEmpty()) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "需求说明不能为空");
        }
        
        return ResultUtils.success(null);
    }

    /**
     * 解析服务时间字符串，支持多种ISO格式
     */
    private Date parseServiceTime(String serviceTimeStr) throws Exception {
        serviceTimeStr = serviceTimeStr.trim();
        
        try {
            Instant instant = Instant.parse(serviceTimeStr);
            return Date.from(instant);
        } catch (Exception e1) {
            log.warn("使用Instant.parse解析失败，尝试其他格式");
            throw new Exception("无法解析时间字符串: " + serviceTimeStr);
        }
    }
}
